const express = require('express');
const mysql = require('mysql');
const bcrypt = require('bcrypt');
const cors = require('cors');
const bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
const path = require('path');
const fs = require('fs');
const app = express();

// 使用 express-fileupload 中间件
app.use(fileUpload());

app.use(bodyParser.json());
app.use(express.json());
app.use(cors());


const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'mf4B0zc4bFQGQQRcNUze',
  database: 'bronze_atrifacts',
});

// 连接到数据库
db.connect((err) => {
  if (err) {
    console.error('Database connection failed:', err);
  } else {
    console.log('Successfully connected to the database');
  }
});

// 获取文物列表
app.get('/api/artifacts', (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const pageSize = parseInt(req.query.pageSize) || 12;
  const category = req.query.category;
  const era = req.query.era;
  const offset = (page - 1) * pageSize;

  let sql = 'SELECT * FROM artifacts';
  let params = [];
  let conditions = [];

  if (category) {
    conditions.push('class = ?');
    params.push(category);
  }

  const eraMappings = {
    '商': ['商'],
    '西周': ['西周'],
    '春秋': ['春秋'],
    '战国': ['战国', '戰國']
  };

  if (era) {
    const eraKeywords = eraMappings[era] || [era];
    let eraCondition = eraKeywords.map(() => 'era LIKE ?').join(' OR ');
    conditions.push(`(${eraCondition})`);
    eraKeywords.forEach(keyword => {
      params.push(`%${keyword}%`);
    });
  }

  if (conditions.length > 0) {
    sql += ' WHERE ' + conditions.join(' AND ');
  }

  sql += ' LIMIT ? OFFSET ?';
  params.push(pageSize, offset);

  db.query(sql, params, (err, results) => {
    if (err) {
      console.error('Error querying database:', err);
      res.status(500).json({ error: 'Internal server error' });
      return;
    }
    res.json(results);
  });
});

// 注册路由
app.post('/api/register', async (req, res) => {
  const { username, password } = req.body;
  
  try {
    db.query('SELECT * FROM users WHERE username = ?', [username], async (err, results) => {
      if (err) {
        res.status(500).json({ success: false, message: '服务器错误' });
        return;
      }
      
      if (results.length > 0) {
        res.json({ success: false, message: '用户名已存在' });
        return;
      }
      
      const hashedPassword = await bcrypt.hash(password, 10);
      
      db.query('INSERT INTO users (username, password) VALUES (?, ?)', [username, hashedPassword], (err, result) => {
        if (err) {
          res.status(500).json({ success: false, message: '注册失败' });
        } else {
          res.json({ success: true, message: '注册成功' });
        }
      });
    });
  } catch (error) {
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 登录路由
app.post('/api/login', (req, res) => {
  const { username, password } = req.body;
  
  db.query('SELECT * FROM users WHERE username = ?', [username], async (err, results) => {
    if (err) {
      res.status(500).json({ success: false, message: '服务器错误' });
      return;
    }
    
    if (results.length === 0) {
      res.json({ success: false, message: '用户名或密码错误' });
      return;
    }
    
    const user = results[0];
    const match = await bcrypt.compare(password, user.password);
    
    if (match) {
      res.json({ success: true, message: '登录成功', id: user.id });
    } else {
      res.json({ success: false, message: '用户名或密码错误' });
    }
  });
});

// 提交反馈
app.post('/api/feedback', (req, res) => {
  const { feedback } = req.body;
  
  if (!feedback) {
    return res.status(400).json({ error: 'Feedback content is required' });
  }

  const query = 'INSERT INTO feedback (content) VALUES (?)';
  db.query(query, [feedback], (err, result) => {
    if (err) {
      console.error('Error inserting feedback:', err);
      return res.status(500).json({ error: 'Failed to submit feedback' });
    }
    res.status(201).json({ message: 'Feedback submitted successfully', id: result.insertId });
  });
});

// 获取随机问题
app.get('/api/question', (req, res) => {
  const query = 'SELECT * FROM bronze_q_and_a ORDER BY RAND() LIMIT 1';
  db.query(query, (err, results) => {
    if (err) {
      res.status(500).json({ error: 'Error fetching question' });
      return;
    }
    res.json(results[0]);
  });
});

// 获取随机问题（支持获取多道题目）
app.get('/api/questions', (req, res) => {
  const count = parseInt(req.query.count, 10) || 10; // 默认获取10道题
  const query = 'SELECT * FROM bronze_q_and_a ORDER BY RAND() LIMIT ?';
  db.query(query, [count], (err, results) => {
    if (err) {
      res.status(500).json({ error: 'Error fetching questions' });
      return;
    }
    res.json(results);
  });
});


// 提交答案
app.post('/api/answer', (req, res) => {
  const { questionId, answer } = req.body;
  const query = 'SELECT answer FROM bronze_q_and_a WHERE question_id = ?';
  db.query(query, [questionId], (err, results) => {
    if (err) {
      res.status(500).json({ error: 'Error checking answer' });
      return;
    }
    const correctAnswer = results[0].answer;
    const correct = answer === correctAnswer;
    res.json({ correct, correctAnswer });
  });
});

// 收藏问题
app.post('/api/collect', (req, res) => {
  const { userId, questionId } = req.body;
  const query = 'INSERT INTO collected_questions (user_id, question_id) VALUES (?, ?)';
  
  db.query(query, [userId, questionId], (err, result) => {
    if (err) {
      console.error('Error collecting question:', err);
      res.status(500).json({ error: 'Failed to collect question' });
    } else {
      res.status(200).json({ message: 'Question collected successfully' });
    }
  });
});

// 获取收藏的问题
app.get('/api/collected-questions/:userId', (req, res) => {
  const userId = req.params.userId;

  const query = `
    SELECT bq.question_id, bq.question, bq.optionA, bq.optionB, bq.optionC, bq.optionD, bq.answer
    FROM collected_questions cq
    JOIN bronze_q_and_a bq ON cq.question_id = bq.question_id
    WHERE cq.user_id = ?
  `;

  db.query(query, [userId], (error, results) => {
    if (error) {
      console.error('查询数据库出错:', error);
      res.status(500).json({ error: '服务器内部错误' });
    } else {
      res.json(results);
    }
  });
});

// 取消收藏问题
app.delete('/api/uncollect', (req, res) => {
  const { userId, questionId } = req.body;
  const query = 'DELETE FROM collected_questions WHERE user_id = ? AND question_id = ?';
  
  db.query(query, [userId, questionId], (err, result) => {
    if (err) {
      console.error('Error uncollecting question:', err);
      res.status(500).json({ error: 'Failed to uncollect question' });
    } else {
      if (result.affectedRows > 0) {
        res.status(200).json({ message: 'Question uncollected successfully' });
      } else {
        res.status(404).json({ error: 'Question not found in collection' });
      }
    }
  });
});

// 获取新闻
app.get('/api/news', (req, res) => {
  res.set('Cache-Control', 'no-store');

  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 5;
  const offset = (page - 1) * limit;
  const allowedSortBy = ['date', 'likes'];
  const sortBy = allowedSortBy.includes(req.query.sortBy) ? req.query.sortBy : 'date';
  const order = 'DESC';

  const query = `SELECT * FROM news WHERE flag = 1 ORDER BY ?? ${order} LIMIT ? OFFSET ?`;
  const queryParams = [sortBy, limit, offset];

  db.query(query, queryParams, (err, results) => {
    if (err) {
      res.status(500).json({ error: '获取新闻失败' });
      return;
    }

    res.json({
      data: results
    });
  });
});

// 获取用户信息
app.get('/api/users/:id', (req, res) => {
  const userId = req.params.id;
  const query = 'SELECT username FROM users WHERE id = ?';
  db.query(query, [userId], (err, results) => {
    if (err) {
      res.status(500).json({ error: '获取用户信息失败' });
      return;
    }
    if (results.length === 0) {
      res.status(404).json({ error: '用户不存在' });
      return;
    }
    res.json({ username: results[0].username });
  });
});

// 获取用户发布的新闻
app.get('/api/news/myPosts', (req, res) => {
  const userId = req.query.userId;
  if (!userId) {
    return res.status(400).json({ error: '缺少 userId 参数' });
  }

  // 获取用户名
  const getUserQuery = 'SELECT username FROM users WHERE id = ?';
  db.query(getUserQuery, [userId], (userErr, userResults) => {
    if (userErr) {
      return res.status(500).json({ error: '获取用户信息失败' });
    }
    if (userResults.length === 0) {
      return res.status(404).json({ error: '用户不存在' });
    }
    const username = userResults[0].username;

    // 获取用户发布的新闻
    const query = `SELECT * FROM news WHERE author = ? ORDER BY date DESC LIMIT ? OFFSET ?`;
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 5;
    const offset = (page - 1) * limit;
    db.query(query, [username, limit, offset], (err, results) => {
      if (err) {
        res.status(500).json({ error: '获取用户发布的新闻失败' });
        return;
      }
      res.json({
        data: results
      });
    });
  });
});

// 点赞新闻
app.post('/api/news/:id/like', (req, res) => {
  const newsId = req.params.id;
  const query = 'UPDATE news SET likes = likes + 1 WHERE id = ?';
  db.query(query, [newsId], (err, result) => {
    if (err) {
      res.status(500).json({ success: false, error: '点赞失败' });
      return;
    }
    res.json({ success: true, message: '点赞成功' });
  });
});

// 收藏新闻
app.post('/api/news/:id/favorite', (req, res) => {
  const newsId = req.params.id;
  const userId = req.body.userId;

  const checkQuery = 'SELECT * FROM favorites WHERE user_id = ? AND news_id = ?';
  db.query(checkQuery, [userId, newsId], (checkErr, checkResult) => {
    if (checkErr) {
      res.status(500).json({ error: '检查收藏状态失败' });
      return;
    }

    if (checkResult.length > 0) {
      res.status(400).json({ error: '该新闻已收藏' });
      return;
    }

    const insertQuery = 'INSERT INTO favorites (user_id, news_id) VALUES (?, ?)';
    db.query(insertQuery, [userId, newsId], (insertErr, insertResult) => {
      if (insertErr) {
        res.status(500).json({ error: '收藏失败' });
        return;
      }
      res.json({ message: '收藏成功' });
    });
  });
});

// 获取用户收藏的新闻
app.get('/api/users/:id/favorites', (req, res) => {
  const userId = req.params.id;

  const query = `
    SELECT news.id, news.title, news.date, news.author, news.summary, news.link, news.likes
    FROM favorites
    INNER JOIN news ON favorites.news_id = news.id
    WHERE favorites.user_id = ?
  `;

  db.query(query, [userId], (err, results) => {
    if (err) {
      console.error('查询失败：', err);
      res.status(500).json({ error: '获取收藏失败' });
      return;
    }
    res.json(results);
  });
});

// 取消收藏新闻
app.delete('/api/news/:id/delete_favorite', (req, res) => {
  const newsId = req.params.id;
  const userId = req.body.userId;

  const query = 'DELETE FROM favorites WHERE user_id = ? AND news_id = ?';
  db.query(query, [userId, newsId], (err, result) => {
    if (err) {
      console.error('取消收藏失败：', err);
      res.status(500).json({ error: '取消收藏失败' });
      return;
    }
    
    if (result.affectedRows === 0) {
      res.status(404).json({ error: '未找到该收藏' });
      return;
    }
    
    res.json({ message: '取消收藏成功' });
  });
});

// 确保图片存储目录存在
const imagesDir = path.join(__dirname, 'news_images');
if (!fs.existsSync(imagesDir)) {
  fs.mkdirSync(imagesDir, { recursive: true });
}

// 处理 JSON 和表单数据
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 图片上传路由
app.post('/api/news_images_upload', async (req, res) => {
  if (!req.files || !req.files.image) {
    return res.status(400).json({ error: '没有上传图片文件' });
  }

  const image = req.files.image;

  // 验证图片类型
  const allowedTypes = /jpeg|jpg|png|gif/;
  const extName = path.extname(image.name).toLowerCase();
  if (!allowedTypes.test(extName)) {
    return res.status(400).json({ error: '仅支持图片文件（jpeg, jpg, png, gif）' });
  }

  // 生成唯一文件名
  const uniqueName = `${Date.now()}${extName}`;
  const savePath = path.join(imagesDir, uniqueName);

  try {
    // 保存文件
    await image.mv(savePath);

    // 构建图片URL
    const imageUrl = `/news_images/${uniqueName}`;

    res.json({ imageUrl });
  } catch (err) {
    console.error('保存图片时出错:', err);
    res.status(500).json({ error: '保存图片失败' });
  }
});

// 静态文件服务
app.use('/news_images', express.static(imagesDir));

// 提交新闻路由（修改后）
app.post('/api/news/submit', (req, res) => {
  const { userId, title, summary, link, image_url } = req.body;
  
  if (!userId || !title || !summary) {
    return res.status(400).json({ error: '缺少必要的字段' });
  }
  
  const getUserQuery = 'SELECT username FROM users WHERE id = ?';
  db.query(getUserQuery, [userId], (userErr, userResult) => {
    if (userErr) {
      console.error('获取用户时出错:', userErr);
      return res.status(500).json({ error: '内部服务器错误' });
    }
    if (userResult.length === 0) {
      return res.status(404).json({ error: '用户不存在' });
    }
    const username = userResult[0].username;

    const today = new Date().toISOString().split('T')[0];

    const insertNewsQuery = 'INSERT INTO news (title, date, author, summary, link, likes, flag, image_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?)';
    db.query(insertNewsQuery, [title, today, username, summary, link || '', 0, 0, image_url || null], (insertErr, insertResult) => {
      if (insertErr) {
        console.error('插入新闻时出错:', insertErr);
        return res.status(500).json({ error: '插入新闻失败' });
      }
      return res.json({ message: '新闻提交成功，等待审核' });
    });
  });
});

// 删除用户自己的新闻
app.delete('/api/news/:id', (req, res) => {
  const newsId = req.params.id;
  const userId = req.body.userId;

  if (!userId) {
    return res.status(400).json({ success: false, error: '缺少 userId 参数' });
  }

  // 获取用户名
  const getUserQuery = 'SELECT username FROM users WHERE id = ?';
  db.query(getUserQuery, [userId], (userErr, userResults) => {
    if (userErr) {
      console.error('获取用户信息失败:', userErr);
      return res.status(500).json({ success: false, error: '获取用户信息失败' });
    }
    if (userResults.length === 0) {
      return res.status(404).json({ success: false, error: '用户不存在' });
    }
    const username = userResults[0].username;

    // 获取新闻信息
    const getNewsQuery = 'SELECT author FROM news WHERE id = ?';
    db.query(getNewsQuery, [newsId], (newsErr, newsResults) => {
      if (newsErr) {
        console.error('获取新闻信息失败:', newsErr);
        return res.status(500).json({ success: false, error: '获取新闻信息失败' });
      }
      if (newsResults.length === 0) {
        return res.status(404).json({ success: false, error: '新闻不存在' });
      }
      const newsAuthor = newsResults[0].author;

      // 验证用户是否是作者
      if (newsAuthor !== username) {
        return res.status(403).json({ success: false, error: '您无权删除这条新闻' });
      }

      // 删除新闻
      const deleteNewsQuery = 'DELETE FROM news WHERE id = ?';
      db.query(deleteNewsQuery, [newsId], (deleteErr, deleteResult) => {
        if (deleteErr) {
          console.error('删除新闻失败:', deleteErr);
          return res.status(500).json({ success: false, error: '删除新闻失败' });
        }
        res.json({ success: true, message: '新闻删除成功' });
      });
    });
  });
});


// 获取博物馆信息
app.get('/api/museums', (req, res) => {
  const sql = 'SELECT * FROM museums';
  db.query(sql, (err, results) => {
    if (err) throw err;
    res.json(results);
  });
});

// 获取古青铜遗址信息
app.get('/api/bronze_sites', (req, res) => {
  const sql = 'SELECT * FROM bronze_sites';
  db.query(sql, (err, results) => {
    if (err) {
      console.error('Error fetching bronze sites:', err);
      return res.status(500).json({ error: '数据库查询失败' });
    }
    res.json(results);
  });
});

// ===================== 新增收藏文物的路由 =====================

// 收藏文物 - 添加收藏
app.post('/api/artifacts/:id/favorite', (req, res) => {
  const artifactId = req.params.id;
  const userId = req.body.userId;

  if (!userId || !artifactId) {
    return res.status(400).json({ message: '缺少 userId 或 artifactId' });
  }

  const checkQuery = 'SELECT * FROM artifacts_favorites WHERE user_id = ? AND artifact_id = ?';
  db.query(checkQuery, [userId, artifactId], (checkErr, checkResult) => {
    if (checkErr) {
      console.error('检查收藏状态失败:', checkErr);
      return res.status(500).json({ message: '检查收藏状态失败' });
    }

    if (checkResult.length > 0) {
      return res.status(409).json({ message: '该文物已被收藏' }); // 修改为 409 Conflict
    }

    const insertQuery = 'INSERT INTO artifacts_favorites (user_id, artifact_id) VALUES (?, ?)';
    db.query(insertQuery, [userId, artifactId], (insertErr, insertResult) => {
      if (insertErr) {
        console.error('添加收藏失败:', insertErr);
        return res.status(500).json({ message: '添加收藏失败' });
      }
      res.status(201).json({ message: '收藏成功' }); // 添加 201 Created 状态码
    });
  });
});


// 取消收藏文物
app.delete('/api/artifacts/:id/favorite', (req, res) => {
  const artifactId = req.params.id;
  const userId = req.body.userId;

  if (!userId || !artifactId) {
    return res.status(400).json({ message: '缺少 userId 或 artifactId' });
  }

  const deleteQuery = 'DELETE FROM artifacts_favorites WHERE user_id = ? AND artifact_id = ?';
  db.query(deleteQuery, [userId, artifactId], (err, result) => {
    if (err) {
      console.error('取消收藏失败:', err);
      return res.status(500).json({ message: '取消收藏失败' });
    }

    if (result.affectedRows > 0) {
      res.json({ message: '取消收藏成功' });
    } else {
      res.status(404).json({ message: '收藏记录不存在' });
    }
  });
});

// 获取用户的文物收藏列表
app.get('/api/users/:userId/artifact-favorites', (req, res) => {
  const userId = req.params.userId;

  if (!userId) {
    return res.status(400).json({ message: '缺少 userId' });
  }

  const query = 'SELECT artifact_id FROM artifacts_favorites WHERE user_id = ?';
  db.query(query, [userId], (err, results) => {
    if (err) {
      console.error('获取收藏列表失败:', err);
      return res.status(500).json({ message: '服务器内部错误' });
    }

    res.status(200).json(results);
  });
});

// 获取用户收藏的文物详情列表
app.get('/api/users/:userId/artifact-favorites-details', (req, res) => {
  const userId = req.params.userId;

  if (!userId) {
    return res.status(400).json({ message: '缺少 userId' });
  }

  const query = `
    SELECT a.* FROM artifacts a
    JOIN artifacts_favorites af ON a.id = af.artifact_id
    WHERE af.user_id = ?
  `;
  db.query(query, [userId], (err, results) => {
    if (err) {
      console.error('获取收藏文物详情失败:', err);
      return res.status(500).json({ message: '服务器内部错误' });
    }

    res.status(200).json(results);
  });
});

// ==================================================================

// 收藏模型 - 添加收藏
app.post('/api/models/:modelId/favorite', (req, res) => {
  const modelId = req.params.modelId;
  const userId = req.body.userId;

  if (!userId || !modelId) {
    return res.status(400).json({ message: '缺少 userId 或 modelId' });
  }

  const checkQuery = 'SELECT * FROM model_favorites WHERE user_id = ? AND model_id = ?';
  db.query(checkQuery, [userId, modelId], (checkErr, checkResult) => {
    if (checkErr) {
      console.error('检查收藏状态失败:', checkErr);
      return res.status(500).json({ message: '检查收藏状态失败' });
    }

    if (checkResult.length > 0) {
      return res.status(409).json({ message: '该模型已被收藏' }); // 409 Conflict
    }

    const insertQuery = 'INSERT INTO model_favorites (user_id, model_id) VALUES (?, ?)';
    db.query(insertQuery, [userId, modelId], (insertErr, insertResult) => {
      if (insertErr) {
        console.error('添加收藏失败:', insertErr);
        return res.status(500).json({ message: '添加收藏失败' });
      }
      res.status(201).json({ message: '收藏成功' });
    });
  });
});

// 取消收藏模型
app.delete('/api/models/:modelId/favorite', (req, res) => {
  const modelId = req.params.modelId;
  const userId = req.body.userId;

  if (!userId || !modelId) {
    return res.status(400).json({ message: '缺少 userId 或 modelId' });
  }

  const deleteQuery = 'DELETE FROM model_favorites WHERE user_id = ? AND model_id = ?';
  db.query(deleteQuery, [userId, modelId], (err, result) => {
    if (err) {
      console.error('取消收藏失败:', err);
      return res.status(500).json({ message: '取消收藏失败' });
    }

    if (result.affectedRows > 0) {
      res.json({ message: '取消收藏成功' });
    } else {
      res.status(404).json({ message: '收藏记录不存在' });
    }
  });
});

// 获取用户的模型收藏列表
app.get('/api/users/:userId/model-favorites', (req, res) => {
  const userId = req.params.userId;

  if (!userId) {
    return res.status(400).json({ message: '缺少 userId' });
  }

  const query = 'SELECT model_id FROM model_favorites WHERE user_id = ?';
  db.query(query, [userId], (err, results) => {
    if (err) {
      console.error('获取收藏列表失败:', err);
      return res.status(500).json({ message: '服务器内部错误' });
    }

    res.status(200).json(results);
  });
});

// 管理员登录
app.post('/api/admin/login', (req, res) => {
  const { password } = req.body;
  const ADMIN_PASSWORD = 'FA1DF04FA51BCF229F0CF76A82037068D46ED1B67FE95FD451D596BE172C9078'; // 请替换为实际的管理员密码，并妥善保管

  if (password === ADMIN_PASSWORD) {
    // 简单示例，实际应用中应返回 token
    res.json({ success: true, message: '登录成功' });
  } else {
    res.status(401).json({ success: false, message: '密码错误' });
  }
});

// 获取待审核的新闻
app.get('/api/admin/news/pending', (req, res) => {
  // 简单示例，实际应用中应进行身份验证
  const query = `SELECT * FROM news WHERE flag = 0 ORDER BY date DESC`;
  db.query(query, (err, results) => {
    if (err) {
      res.status(500).json({ success: false, error: '获取待审核的新闻失败' });
      return;
    }
    res.json({ success: true, data: results });
  });
});

// 审核通过新闻
app.post('/api/admin/news/:id/approve', (req, res) => {
  const newsId = req.params.id;
  const updateQuery = 'UPDATE news SET flag = 1 WHERE id = ?';
  db.query(updateQuery, [newsId], (err, result) => {
    if (err) {
      res.status(500).json({ success: false, error: '审核失败' });
      return;
    }
    if (result.affectedRows === 0) {
      res.status(404).json({ success: false, error: '未找到该新闻' });
      return;
    }
    res.json({ success: true, message: '审核通过' });
  });
});

// 审核失败新闻
app.post('/api/admin/news/:id/reject', (req, res) => {
  const newsId = req.params.id;
  const updateQuery = 'UPDATE news SET flag = -1 WHERE id = ?';
  db.query(updateQuery, [newsId], (err, result) => {
    if (err) {
      res.status(500).json({ success: false, error: '审核失败' });
      return;
    }
    if (result.affectedRows === 0) {
      res.status(404).json({ success: false, error: '未找到该新闻' });
      return;
    }
    res.json({ success: true, message: '审核失败' });
  });
});


// 启动服务器
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});
